package com.xiaouyudeguang.common.client;

import com.fasterxml.jackson.databind.JsonNode;
import com.xiaouyudeguang.common.collect.MapBuilder;
import com.xiaouyudeguang.common.utils.JsonObject;
import com.xiaouyudeguang.common.utils.RestTemplateUtils;

public class AppletClient {

    /**
     * 小程序登录(https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html)
     * @param appKey
     * @param secret
     * @param code
     * @return
     * @throws Exception
     */
    public static JsonNode loginByCode(String appKey, String secret, String code) throws Exception {
        String API_URL = "https://api.weixin.qq.com/sns/jscode2session?appid={1}&secret={2}&js_code={3}&grant_type=authorization_code";
        String result = RestTemplateUtils.getForObject(API_URL, String.class, appKey, secret, code);
        return JsonObject.readTree(result);
    }

    /**
     * 小程序手机号快速登录(https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html)
     * @param appKey
     * @param secret
     * @param code
     * @return
     * @throws Exception
     */
    public static JsonNode getPhone(String appKey, String secret, String code) throws Exception {
        String API_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={1}";
        String result = RestTemplateUtils.postForObject(API_URL, MapBuilder.of("code", code), String.class, CommonClient.getToken(appKey, secret));
        return JsonObject.readTree(result);
    }
}
